package compiler.terminals;

import compiler.HowlToken;
import compiler.HowlType;
import compiler.TokenReader;
import compiler.exceptions.HowlParserException;
import compiler.terminals.expression.Node;
import compiler.terminals.expression.OpFactory;
import compiler.terminals.expression.Operator;
import compiler.terminals.expression.Statement;

public class BooleanExpression extends HowlToken {
	
	private Node exp;

	public BooleanExpression(TokenReader tokenReader) {
		super(tokenReader);
	}

	@Override
	public String codeGenerate() {
		return this.exp.toString();
	}

	@Override
	public HowlToken parse() throws HowlParserException {
		
		this.exp = lex();
		return this;

	}
	
	private Node lex() {
		

		Node tmp = null;
		String lookahead = this.tokenReader.nextToken();
		if(!lookahead.startsWith("(")) {
		
			tmp = new Statement(this.tokenReader);
			if(this.tokenReader.hasMoreTokens() && !(this.tokenReader.nextToken().equals(";") ||this.tokenReader.nextToken().equals(")")) ){
				Operator h = OpFactory.makeOperator(this.tokenReader.consumeToken());
				
				h.setLeft(tmp);
				h.setRight(this.lex());
				tmp = h;
			} else {
				//this.map = tmp;
				return tmp;
			}
		}else if(lookahead.startsWith("(")) {
			this.tokenReader.consumeToken();
			tmp = this.lex();
			
			if(this.tokenReader.nextToken().equals(")")){
				this.tokenReader.consumeToken();
				if(this.tokenReader.hasMoreTokens()){
			
				Operator h = OpFactory.makeOperator(this.tokenReader.consumeToken());
				
				h.setLeft(tmp);
				h.setRight(this.lex());
				tmp = h;
				}
			} else {
				//this.map = tmp;
				return tmp;
			}
		}
		
		
		
		return tmp;

	}
	
	/**
	 * @return the exp
	 */
	public Node getExp() {
		return exp;
	}

	/**
	 * @param exp the exp to set
	 */
	public void setExp(Node exp) {
		this.exp = exp;
	}

}
